home *** CD-ROM | disk | FTP | other *** search
- ===========================================================================
- BBS: The Abacus * HST/DS * Potterville, MI
- Date: 04-23-93 (22:26) Number: 79
- From: JERRY COFFIN Refer#: NONE
- To: ALL Recvd: NO
- Subj: strrep.c Conf: (36) C Language
- ---------------------------------------------------------------------------
- Recently I posted a routine to find a substring and replace it
- with another. Unluckily, I wrote it, tested it, modified it, and
- then posted the first ( incorrect ) version. With my sincere
- apologies, here's a version that works:
-
- #include <string.h>
-
- /* public domain by Jerry Coffin. Tested with MS C 7.0
- * I believe this should be portable to just about anything
- * that compiles C.
- */
-
- char *str_replace(char *string, char *old, char *new, size_t max_len) {
- /* 'max_len' is the maximum number of characters to place in
- * 'string' If set to anything less than the current size of the
- * string ( eg. 0 ) the string will not be allowed to grow beyond
- * its current length.
- */
-
- char *pos=string;
- size_t len = strlen(string);
- size_t old_len = strlen(old);
- size_t new_len = strlen(new);
- int difference = new_len - old_len;
-
- if (max_len < len )
- max_len = len;
-
- while ( NULL != (pos = strstr(pos,old)) )
- if ( len + difference > max_len )
- break;
- else {
- if ( 0 != difference )
- memmove(pos+new_len,pos+old_len,len-old_len+1);
- strncpy(pos,new,new_len);
- len += difference;
- pos+= new_len;
- }
- return string;
- }
-
- #ifdef TEST
- #include <stdio.h>
-
- int main(void) {
- char something[100] = "This @bad_name is a bunch of @bad_name";
-
- printf("old string: %s\n",something);
- str_replace(something,"@bad_name","garbage",100);
- printf("new string: %s\n",something);
- str_replace(something," garbage"," garbage.",100);
- printf("changed again: %s\n",something);
- return 0;
- }
- #endif
-
- Again, my apologies for the incorrect version.
- Later,
- Jerry.
-
- --- PPoint 1.38
- * Origin: Point Pointedly Pointless (1:128/77.3)
- SEEN-BY: 1/211 11/2 4 13/13 101/1 108/89 109/25 110/69 114/5 123/19 124/1
- SEEN-BY: 153/752 154/40 77 157/2 159/100 125 575 950 203/23 209/209 280/1
- SEEN-BY: 390/1 396/1 5 15 2270/1 2440/5 3603/20
-